package manager.cms.service.exec;
import common.*;
import manager.brand.dao.BrandDao;
import manager.brand.vo.BrandVO;
import manager.cms.service.JdExecutor;
import manager.cms.service.utils.JdInternetWormUtils;
import manager.feign.ItemJdThirdService;
import manager.feign.SpuDescriptionThirdService;
import manager.fileupload.service.FileUploadService;
import manager.goods.dao.*;
import manager.goods.service.GoodsService;
import manager.goods.vo.*;
import manager.search.repository.GoodsRepository;
import manager.search.service.SearchService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service(value = "skuAsyncExec")
public class SkuAsyncExecImpl implements JdExecutor {
    @Autowired
    private SpuDescriptionThirdService spuDescriptionThirdService;
    @Autowired
    private ItemJdThirdService itemJdThirdService;
    @Autowired
    private SpuDao spuDao;
    @Autowired
    private SkuDao skuDao;
    @Autowired
    private StockDao stockDao;
    @Autowired
    private SpuDetialDao spuDetialDao;
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private BrandDao brandDao;
    @Autowired
    private GoodsService goodsService;
//    @Autowired
//    private SearchService searchService;
    @Autowired
    private SpuImageLogDao spuImageLogDao;
    @Override
    public void execute(Map<String,Object> mapParams) {
            try {
                List<Map<String,String>> skuDatas=(List<Map<String,String>>)mapParams.get("skuList");
                ThreadPoolExecutor executor= ThreadPoolUtils.getThreadPoolExecutor();
                skuDatas.forEach(skuData->{
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    executor.execute(()->{
                        this.genSpuData(skuData.get("skuId"),skuData.get("categoryId"));
                    });
                });
            }catch (Exception e){
                 e.printStackTrace();
            }
    }
    @Transactional
    public synchronized Boolean genSpuData(String skuId,String categoryId){
          try {
              List<String> spuImages=new ArrayList<>();
              SpuVO spuVO=new SpuVO();
              String id=String.valueOf(SnowflakeIdWorker.nextId());
              spuVO.setId(id);
              spuVO.setRecommond(true);
              String itemHtml=itemJdThirdService.getDetial(skuId);
              //处理规格参数信息结束
              System.out.println("看看里面执行多少次");
              String spuName=getSpuName(itemHtml);
              if(spuName.equals("")){
                  return false;
              }
              spuVO.setTitle(spuName);
              spuVO.setCategoryId(categoryId);
              Map<String,Object> paramsResult=JdInternetWormUtils.getSpecTemplete(itemHtml,true);
              List<SkuVO> skuList=addSkus(paramsResult,id,spuName,spuImages);
              if(skuList==null||skuList.size()==0){
                  return false;
              }
              SpuDetialVO detialVO=new SpuDetialVO();
              detialVO.setSpuId(id);
              Map<String,Object> paramsTempleteData=JdInternetWormUtils.getTemplete(itemHtml);
              detialVO.setSpecifications((String)paramsTempleteData.get("paramsDataStr"));
              //解析品牌ID
              Map<String,Object> paramsData=(Map<String, Object>) paramsTempleteData.get("paramsData");
              List<Map<String,Object>> params=(List<Map<String,Object>>)paramsData.get("params");
              params.forEach(item->{
                  if(item.get("k").equals("品牌")){
                       String brandName=(String)item.get("v");
                       addBrandId(spuVO);
                       spuVO.setBrandName(brandName);
                  }
              });
              String descStr = getDescriptionString(skuId,spuImages);
              if("".equals(descStr)){
                  return false;
              }
              detialVO.setDescription(descStr);
              if(skuList.size()>0){
                  List<StockVO> stocks=new ArrayList<StockVO>();
                  skuList.forEach(stocItem->{
                      StockVO stockVO=new StockVO();
                      stockVO.setSkuId(stocItem.getId());
                      stockVO.setStock(1000);
                      stockVO.setSeckillStock("0");
                      stockVO.setSeckillTotal("0");
                      stocks.add(stockVO);
                  });
                  skuDao.saveSkus(skuList);
                  stockDao.saveStocks(stocks);
                  spuDao.saveSpu(spuVO);
                  spuDetialDao.saveSpuDetial(detialVO);
              }
              Pager pager=new Pager();
              pager.setPageSize(1);
              spuVO.setPager(pager);
              pager.setCurrentPage(1);
              spuVO.setFromDb(true);
              spuVO.setId(spuVO.getId());
              PageView<List<SpuVO>> pageView=goodsService.selectByConditionPage(spuVO);
              //将数据插入
              if(pageView.getRows().size()>0){
//                  searchService.saveDbToEs(pageView.getRows().get(0));
                  //插入图片和
                  List<SpuImageLogVO> list=new ArrayList<>();
                  spuImages.forEach(item->{
                      SpuImageLogVO spuImageLogVO=new SpuImageLogVO();
                      spuImageLogVO.setSpuId(id);
                      spuImageLogVO.setImageUrl(item);
                      list.add(spuImageLogVO);
                  });
                  spuImageLogDao.insertList(list);
              }

          }catch (Exception e){
              e.printStackTrace();;
          }
          return true;
    }

    /**
     * 根据品牌名称获取品牌ID
     * @param spuVO
     */
    private void addBrandId(SpuVO spuVO){
            Example example = new Example(BrandVO.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("name",spuVO.getBrandName());
            List<BrandVO> searchSpecParams=brandDao.selectByExample(example);
            if(searchSpecParams.size()>0){
                String brandId=searchSpecParams.get(0).getId();
                spuVO.setBrandId(brandId);
            }

    }

    /**
     * 加入sku
     * @param paramsResult
     * @param id
     * @param spuName
     * @return
     * @throws Exception
     */
    public List<SkuVO> addSkus(Map<String,Object> paramsResult,String id,String spuName,List<String> imageList) throws Exception{
        JSONArray skuArray=(JSONArray)paramsResult.get("skuArray");
        List<SkuVO> skuList=new ArrayList<SkuVO>();
        //获取特有规格参数
        List<Map<String,Object>> params=(List<Map<String,Object>>)paramsResult.get("specialParams");
        if(skuArray==null){
            return skuList;
        }
        for (int j=0;j<skuArray.length();j++){
            JSONObject skuObj=(JSONObject)skuArray.get(j);
            Iterator<String> skuIterator = skuObj.keys();
            String indexs="";
            Map<String,Object> ownSpec=new HashMap<String,Object>();
            while (skuIterator.hasNext()){
                String key=skuIterator.next();
                if(key=="skuId"){
                    continue;
                }
                List<Map<String,Object>> list=params.stream().filter(paramItem->paramItem.get("k").equals(key)).collect(Collectors.toList());
                if(list.size()>0){
                    Map<String,Object> mapItem=list.get(0);
                    List<Map<String,Object>> options=(List<Map<String,Object>>)mapItem.get("options");
                    String v=skuObj.get(key).toString();
                    ownSpec.put(key,v);
                    List<Map<String,Object>> opItem=options.stream().filter(op->op.get("v").equals(v)).collect(Collectors.toList());
                    if(opItem.size()>0){
                        indexs=indexs+"-"+opItem.get(0).get("index");
                    }
                }
            }
            SkuVO skuVO=getSkuAndStock(skuObj.get("skuId").toString());
            if(skuVO.getImages()==null){
                continue;
            }
            String[] imagesArray=skuVO.getImages().split(",");
            for(int i=0;i<imagesArray.length;i++){
                imageList.add(imagesArray[i]);
            }

            skuVO.setEnable(true);
            skuVO.setPrice("100");
            indexs=indexs.substring(1,indexs.length());
            skuVO.setIndexes(indexs);
            String selectSkuId=String.valueOf(SnowflakeIdWorker.nextId());
            skuVO.setSpuId(id);
            skuVO.setId(selectSkuId);
            skuVO.setTitle(spuName);
            JSONObject ownSpecObj=new JSONObject(ownSpec);
            skuVO.setOwnSpec(ownSpecObj.toString());
            skuList.add(skuVO);
        }
        return skuList;
    }
    public String getSpuName(String itemHtml){
            String pattern = "\"sku-name\">[\\s\\S]*?</div";
            Pattern compile = Pattern.compile(pattern);
            Matcher m=compile.matcher(itemHtml);
            String spuName="";
            while (m.find()){
                spuName=m.group();
                String regex = "<img[^>]*>";
                spuName=spuName.replaceAll(regex, "");
            }
            if(!spuName.equals("")){
                return spuName.substring(13,spuName.length()-5).trim();
            }
            return "";
    }
    public String getDescriptionString(String skuId,List<String> imageList){
            String descStr="";
            try {
                JSONObject jsonObject;
                String itemHtml=itemJdThirdService.getDetial(skuId);
                //正则匹配
                String htmlPattern = "mainSkuId=.*&{1}";
                Pattern htmlCompile = Pattern.compile(htmlPattern);
                Matcher htmlMatcher=htmlCompile.matcher(itemHtml);
                String mainSkuId="";
                while (htmlMatcher.find()){
                    mainSkuId=htmlMatcher.group().substring(10,htmlMatcher.group().length()-1);
                    String[] skuSplitStr=mainSkuId.split("&");
                    mainSkuId=skuSplitStr[0];
                }
                String desc=spuDescriptionThirdService.getDescription(skuId,mainSkuId);
                desc=desc.substring(9,desc.length()-1);
                jsonObject = new JSONObject(desc);
                String data=jsonObject.get("content").toString();
                String pattern = "\\/\\/img.*?\\.jpg";
                Pattern compile = Pattern.compile(pattern);
                String content=data.toString();
                Matcher m=compile.matcher(content);
                while (m.find()) {
                    String image = ImageBase64Utils.base64Img("https:" + m.group(),"1",fileUploadService);
                    imageList.add(image);
                    descStr=descStr+image;
                }
            }catch (Exception e){

            }
            return descStr;
    }
    //获取单个产品的sku信息和库存信息
    public SkuVO getSkuAndStock(String skuId){
            SkuVO skuVO=new SkuVO();
            try {
                //匹配大圖片
                String itemHtml=itemJdThirdService.getDetial(skuId);
                String pattern = "imageList.*?]";
                Pattern compile = Pattern.compile(pattern);
                Matcher m=compile.matcher(itemHtml);
                String imageUrls="";
                while (m.find()){
                    String imgStr=m.group();
                    imgStr=imgStr.substring(11,imgStr.length());
                    JSONArray imageArray=new JSONArray(imgStr);
                    for (int i=0;i<imageArray.length();i++){
                        String image= ImageBase64Utils.base64Img("https://img11.360buyimg.com/n1/"+imageArray.get(i).toString(),"2",fileUploadService);
                        imageUrls=imageUrls+image+",";
                    }
                }
                if(!"".equals(imageUrls)){
                    skuVO.setImages(imageUrls);
                }

            }catch (Exception e){
                e.printStackTrace();
            }
            return skuVO;
    }
}
